<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>我的订单</title>
    <style>
        body {
            font-family: "Microsoft YaHei", sans-serif;
            background: #f8f9fa;
            margin: 0;
            padding: 20px;
        }
        .container {
            max-width: 1000px;
            margin: 0 auto;
        }
        h2 {
            text-align: center;
            color: #333;
            margin: 20px 0;
        }
        .filter {
            text-align: center;
            margin-bottom: 20px;
        }
        .filter select {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .transaction-table {
            width: 100%;
            border-collapse: collapse;
            background: white;
            box-shadow: 0 2px 6px rgba(0,0,0,0.1);
        }
        .transaction-table th, .transaction-table td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #eee;
        }
        .transaction-table th {
            background: #f2f2f2;
            color: #555;
        }
        .status {
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 0.9em;
        }
        .status-pending {
            background: #ffc107;
            color: #333;
        }
        .status-shipping {
            background: #17a2b8;
            color: white;
        }
        .status-completed {
            background: #28a745;
            color: white;
        }
        .status-canceled {
            background: #dc3545;
            color: white;
        }
        .action-btn {
            padding: 6px 12px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin-right: 5px;
            font-size: 0.9em;
        }
        .pay-btn {
            background: #28a745;
            color: white;
        }
        .cancel-btn {
            background: #dc3545;
            color: white;
        }
        .confirm-btn {
            background: #007bff;
            color: white;
        }
        .message {
            text-align: center;
            margin: 50px 0;
            color: #666;
        }
        .back-link {
            display: block;
            text-align: center;
            margin-top: 30px;
            color: #007bff;
            text-decoration: none;
        }
        .back-link:hover {
            text-decoration: underline;
        }
    </style>
</head>
<body>
    <div class="container">
        <h2>我的订单</h2>
        
        <div class="filter">
            <label for="statusFilter">订单状态：</label>
            <select id="statusFilter" onchange="filterTransactions()">
                <option value="">全部订单</option>
                <option value="待付款">待付款</option>
                <option value="待收货">待收货</option>
                <option value="交易完成">交易完成</option>
                <option value="已取消">已取消</option>
            </select>
        </div>
        
        <table class="transaction-table">
            <thead>
                <tr>
                    <th>订单ID</th>
                    <th>艺术品</th>
                    <th>卖家</th>
                    <th>价格</th>
                    <th>时间</th>
                    <th>状态</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody id="transactionBody"></tbody>
        </table>
        
        <div id="message" class="message"></div>
        <a href="index.html" class="back-link">返回首页</a>
    </div>
    <script>
        let currentUserId = null;
        
        window.onload = () => {
            const user = checkLogin();
            if (user) {
                currentUserId = user.user_id;
                loadTransactions();
            }
        };

        function loadTransactions(status = '') {
            const url = new URL(`/transaction/user/${currentUserId}`, window.location.origin);
            if (status) url.searchParams.append('status', status);
            
            fetch(url)
            .then(res => res.json())
            .then(data => {
                const tbody = document.getElementById('transactionBody');
                const msgEl = document.getElementById('message');
                
                if (data.success && data.transactions.length) {
                    tbody.innerHTML = data.transactions.map(trans => `
                        <tr>
                            <td>${trans.transaction_id}</td>
                            <td>
                                <a href="artwork_detail.html?id=${trans.artwork_id}">${trans.artwork_title}</a>
                            </td>
                            <td>${trans.seller_name}</td>
                            <td>¥${trans.transaction_price}</td>
                            <td>${trans.transaction_time}</td>
                            <td>
                                <span class="status status-${getStatusClass(trans.transaction_status)}">
                                    ${trans.transaction_status}
                                </span>
                            </td>
                            <td>
                                ${getActionButtons(trans.transaction_id, trans.transaction_status)}
                            </td>
                        </tr>
                    `).join('');
                    msgEl.textContent = '';
                } else {
                    tbody.innerHTML = '';
                    msgEl.textContent = '暂无订单记录';
                }
            })
            .catch(err => {
                document.getElementById('message').textContent = '加载失败：' + err;
            });
        }

        function filterTransactions() {
            const status = document.getElementById('statusFilter').value;
            loadTransactions(status);
        }

        // 根据状态获取样式类名
        function getStatusClass(status) {
            switch(status) {
                case '待付款': return 'pending';
                case '待收货': return 'shipping';
                case '交易完成': return 'completed';
                case '已取消': return 'canceled';
                default: return '';
            }
        }

        // 根据状态生成操作按钮
        function getActionButtons(transactionId, status) {
            switch(status) {
                case '待付款':
                    return `
                        <button class="action-btn pay-btn" onclick="updateStatus(${transactionId}, '待收货')">付款</button>
                        <button class="action-btn cancel-btn" onclick="updateStatus(${transactionId}, '已取消')">取消</button>
                    `;
                case '待收货':
                    return `
                        <button class="action-btn confirm-btn" onclick="updateStatus(${transactionId}, '交易完成')">确认收货</button>
                    `;
                default:
                    return '无操作';
            }
        }

        // 更新订单状态
        function updateStatus(transactionId, newStatus) {
            const actionText = newStatus === '待收货' ? '付款' : 
                             newStatus === '交易完成' ? '确认收货' : '取消';
            
            if (confirm(`确定要${actionText}此订单吗？`)) {
                fetch('/transaction/status', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        transaction_id: transactionId,
                        status: newStatus
                    })
                })
                .then(res => res.json())
                .then(data => {
                    alert(data.message);
                    if (data.success) {
                        const currentStatus = document.getElementById('statusFilter').value;
                        loadTransactions(currentStatus); // 重新加载订单列表
                    }
                })
                .catch(err => alert('操作失败：' + err));
            }
        }

        function checkLogin() {
            const userStr = localStorage.getItem('userInfo');
            if (!userStr) {
                alert('请先登录');
                location.href = 'login.html';
                return null;
            }
            return JSON.parse(userStr);
        }
    </script>
</body>
</html>
